package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.AlbumMapper;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.pojo.dto.PictureAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.pojo.vo.PictureStandardVo;
import cn.tedu.csmall.product.service.IPictureService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 处理图片的业务层实现类
 * @author 何惠民
 */
@Slf4j
@Service
public class PictureServiceImpl implements IPictureService {

    @Autowired
    PictureMapper pictureMapper;

    @Autowired
    AlbumMapper albumMapper;

    public PictureServiceImpl() {
        log.debug("创建业务层对象:PictureServiceImpl");
    }

    @Override
    public void addNew(PictureAddNewDTO pictureAddNewDTO) {
        log.debug("开始处理添加图片的业务:参数{}",pictureAddNewDTO);

        //查询相册id是否存在
        Long albumId = pictureAddNewDTO.getAlbumId();
        AlbumStandardVO album = albumMapper.getStandardById(albumId);
        if (album == null){
            String message = "ID为" + albumId +"的相册数据不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureAddNewDTO, picture);
        int rows = pictureMapper.insert(picture);
        if (rows != 1){
            String message = "添加图片失败,服务器忙,请稍后再尝试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        log.debug("插入图片数据完成");
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理删除图片的业务");

        //查询图片是否存在
        PictureStandardVo picture = pictureMapper.getStandardById(id);
        if (picture == null){
            String message = "删除图片失败,尝试删除的数据不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        int rows = pictureMapper.deleteById(id);
        if (rows != 1){
            String message = "删除图片失败,服务器忙,请稍后再尝试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
        log.debug("删除图片的业务完成");

    }
}
